/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package scms;

import java.net.*;
import java.io.*;

/**
 *	chat client class
 * @author pumped
 */
public class ChatClient extends ChatAbstract {

	private String ip;
	private Socket client;
	ChatGui gui;

	/**
	 * constructor
	 * @param gui output gui
	 * @param ip server ip
	 * @param port server port
	 */
	public ChatClient(ChatGui gui, String ip, int port) {
		this.ip = ip;
		this.port = port;
		this.gui = gui;

		try {
			client = new Socket(ip, port);

			send = new DataOutputStream(client.getOutputStream());
			recieve = new DataInputStream(client.getInputStream());
		} catch (SocketTimeoutException s) {
			System.out.println("Socket timed out!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Start listening for server updates
	 */
	public void startListen() {
		String message;
		while (true) {
			try {
				message = recieve.readUTF();
				System.out.println(message);
				gui.addMessage(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * thread start point
	 */
	public void run() {
		startListen();
	}

	/**
	 * sends message to server
	 * @param message
	 */
	public void sendMessage(String message) {
		try {
			if (send != null) {
				send.writeUTF(message);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
